
# -*- coding: utf-8 -*-
"""
Part 2  Python基础
"""
'''
2.1 基础语法
'''
#python2
#print "Hello, Python!"
#python3
print ("Hello, Python!")

#行和缩进
if True:
    print("True")
    print('a')
else:
    print("False")


if True:
       print("Answer")
       print("True")
else:
    print("Answer")
        #缩进空格不定，但必须保持一致
    print("False")

#多行语句
item_one=1
item_two=2
item_three=3
total = item_one + item_two + \
        item_three
print(total)

#若是在括号中换行，可省略\
days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']
days

#引号
word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""
print(word)
print(sentence)
print(paragraph)

#注释
# 第一个注释
print("Hello, Python!")  # 第二个注释
name = "Madisetti" # 这是一个注释

'''
这是多行注释，使用单引号。
这是多行注释，使用单引号。
这是多行注释，使用单引号。
'''

"""
这是多行注释，使用双引号。
这是多行注释，使用双引号。
这是多行注释，使用双引号。
"""

#空行
a=input("\n\nPress the enter key to exit.")
a
import sys; x = 'foo'; sys.stdout.write(x + '\n')

print('a');print('b')
print()
#码组
'''
if expression : 
   suite 
elif expression :  
   suite  
else :  
   suite 
'''

#帮助
help(sys.stdout.write)

#变量赋值
counter = 100 # 赋值整型变量
miles = 1000.0 # 浮点型
name = "John" # 字符串

print(counter)
print(miles)
print(name)

a = b = c = 1
print(a,b,c)
a, b, c = 1, 2, "john"
print(a,b,c)

(a,b)=(11,12)
print(a,b,c)
'''
2.2 基本变量类型
'''
#数字
var1 = 1
var2 = 10

#del var1[,var2[,var3[....,varN]]]]
var=5896419821
var_a=-0.22
abs(var_a)
var_b=3e2

if var_a>var_b:
   print('a大')
else:
   print('b大')


del var
del var_a, var_b



#字符串
#s="a1a2•••an"(n>=0)
s = 'ilovepython'
print(s[1:5])
print(s[5:-1])

str = 'Hello World!'
print(str) # 输出完整字符串
print(str[0]) # 输出字符串中的第一个字符
print(str[2:5]) # 输出字符串中第三个至第五个之间的字符串
print(str[2:]) # 输出从第三个字符开始的字符串
print(str * 2) # 输出字符串两次
print(str + "TEST") # 输出连接的字符串
print(len(str))  #长度

#字符串是否包含某个子字符串
str1='ilovepython'
str2='py'
if str2 in str1:
   print('包含')

if str1.find(str2)>=0:
   print(str1.find(str2))
　　#包含的话，返回第一次出现的位置，没有的话为负数

'''
Python int与string之间的转化
string-->int

1、10进制string转化为int

　　int('12')

2、16进制string转化为int

　　int('12', 16)

int-->string

1、int转化为10进制string

　　str(18)

2、int转化为16进制string

　　hex(18)
'''
#列表
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']

print(list) # 输出完整列表
print(list[0]) # 输出列表的第一个元素
print(list[1:3]) # 输出第二个至第三个的元素 
print(list[2:])# 输出从第三个开始至列表末尾的所有元素
print(tinylist * 2)# 输出列表两次
print(list + tinylist)# 打印组合的列表
print(len(list))


import random
 
list = [20, 16, 10, 5]
len(list)
sorted(list)
list
list.sort()
list
random.shuffle(list)
list
'''
>>> d = [2,3,4]
>>> e = [1,2,3]
>>> d.extend(e)  # 用列表用extend（）方法
>>> d
[2, 3, 4, 1, 2, 3]
 

>>> a = {1:[2,3,4]}
>>> b = {2:[3,2,1],3:[4,5,6]}
>>> a.update(b) # 字典用update（）方法
>>> a
{1: [2, 3, 4], 2: [3, 2, 1], 3: [4, 5, 6]}
'''

#元组
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print(tuple)# 输出完整元组
print(tuple[0])# 输出元组的第一个元素
print(tuple[1:3])# 输出第二个至第三个的元素 
print(tuple[2:])# 输出从第三个开始至列表末尾的所有元素
print(tinytuple * 2)# 输出元组两次
print(tuple + tinytuple)# 打印组合的元组

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # 元组中是非法应用
list[2] = 1000 # 列表中是合法应用

#元字典
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, 'dept': 'sales'}


print(dict['one'])# 输出键为'one' 的值
print(dict[2])# 输出键为 2 的值
print(tinydict)# 输出完整的字典
print(tinydict.keys())# 输出所有键
print(tinydict.values())# 输出所有值

dict.shuft

'''
方法一
 dict.has_key(key_name)   #好像已经不可用了
 返回值:True 或者 False
方法二
if key in dict.keys()：
    print "key in dict"
'''


#算术运算符
a = 21
b = 10
c = 0

c = a + b
print("Line 1 - Value of c is ", c)

c = a - b
print("Line 2 - Value of c is ", c)

c = a * b
print("Line 3 - Value of c is ", c)

c = a / b
print("Line 4 - Value of c is ", c) 

c = a % b  #求余
print("Line 5 - Value of c is ", c)

a = 2
b = 3
c = a**b #2的3次方
print("Line 6 - Value of c is ", c)

a = 11
b = 5
c = a//b  #取整
print("Line 7 - Value of c is ", c)

#比较运算符
a = 21
b = 10
c = 0

if ( a == b ):
   print("Line 1 - a is equal to b")
else:
   print("Line 1 - a is not equal to b")

if ( a != b ):
   print("Line 2 - a is not equal to b")
else:
   print("Line 2 - a is equal to b")

if ( a != b ):
   print("Line 3 - a is not equal to b")
else:
   print("Line 3 - a is equal to b")

if ( a < b ):
   print("Line 4 - a is less than b")
else:
   print("Line 4 - a is not less than b")

if ( a > b ):
   print("Line 5 - a is greater than b")
else:
   print("Line 5 - a is not greater than b")

a = 5;
b = 20;
if ( a <= b ):
   print("Line 6 - a is either less than or equal to  b")
else:
   print("Line 6 - a is neither less than nor equal to  b")

if ( b >= a ):
   print("Line 7 - b is either greater than  or equal to b")
else:
   print("Line 7 - b is neither greater than  nor equal to b")

#赋值运算符
a = 21
b = 10
c = 0

c = a + b
print("Line 1 - Value of c is ", c)

c += a
print("Line 2 - Value of c is ", c)

c *= a
print("Line 3 - Value of c is ", c)

c /= a 
print("Line 4 - Value of c is ", c)

c  = 2
c %= a
print("Line 5 - Value of c is ", c)

c **= a
print("Line 6 - Value of c is ", c)

c //= a
print("Line 7 - Value of c is ", c)

#位运算符
a = 60            # 60 = 0011 1100 
b = 13            # 13 = 0000 1101 
c = 0

c = a & b;        # 12 = 0000 1100
print("Line 1 - Value of c is ", c)

c = a | b;        # 61 = 0011 1101 
print("Line 2 - Value of c is ", c)

c = a ^ b;        # 49 = 0011 0001
print("Line 3 - Value of c is ", c)

c = ~a;           # -61 = 1100 0011
print("Line 4 - Value of c is ", c)

c = a << 2;       # 240 = 1111 0000
print("Line 5 - Value of c is ", c)

c = a >> 2;       # 15 = 0000 1111
print("Line 6 - Value of c is ", c)

#逻辑运算符
a = 10
b = 20
c = 0

if ( a and b ):
   print("Line 1 - a and b are true")
else:
   print("Line 1 - Either a is not true or b is not true")

if ( a or b ):
   print("Line 2 - Either a is true or b is true or both are true")
else:
   print("Line 2 - Neither a is true nor b is true")


a = 0
if ( a and b ):
   print("Line 3 - a and b are true")
else:
   print("Line 3 - Either a is not true or b is not true")

if ( a or b ):
   print("Line 4 - Either a is true or b is true or both are true")
else:
   print("Line 4 - Neither a is true nor b is true")

if not( a and b ):
   print("Line 5 - Either a is not true or b is  not true or both are not true")
else:
   print("Line 5 - a and b are true")

#成员运算符
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];

if ( a in list ):
   print("Line 1 - a is available in the given list")
else:
   print("Line 1 - a is not available in the given list")

if ( b not in list ):
   print("Line 2 - b is not available in the given list")
else:
   print("Line 2 - b is available in the given list")

a = 2
if ( a in list ):
   print("Line 3 - a is available in the given list")
else:
   print("Line 3 - a is not available in the given list")

#身份运算符
a = 20
b = 20

if ( a is b ):
   print("Line 1 - a and b have same identity")
else:
   print("Line 1 - a and b do not have same identity")

if ( id(a) == id(b) ):
   print("Line 2 - a and b have same identity")
else:
   print("Line 2 - a and b do not have same identity")

b = 30
if ( a is b ):
   print("Line 3 - a and b have same identity")
else:
   print("Line 3 - a and b do not have same identity")

if ( a is not b ):
   print("Line 4 - a and b do not have same identity")
else:
   print("Line 4 - a and b have same identity")

#运算符优先级
a = 20
b = 10
c = 15
d = 5
e = 0

e = (a + b) * c / d       #( 30 * 15 ) / 5
print("Value of (a + b) * c / d is ",  e)

e = ((a + b) * c) / d     # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ",  e)

e = (a + b) * (c / d);    # (30) * (15/5)
print("Value of (a + b) * (c / d) is ",  e)

e = a + (b * c) / d;      #  20 + (150/5)
print("Value of a + (b * c) / d is ",  e)


'''
2.3 Python语法基础（条件/循环/函数/类/模块）
'''

#条件语句
'''
if 判断条件：
    执行语句……
else：
    执行语句……
'''

flag = False
name = 'python'
if name == 'python':         # 判断变量否为'python'
    flag = True              # 条件成立时设置标志为真
    print('welcome boss')    # 并输出欢迎信息
else:
    print(name)              # 条件不成立时输出变量名称

'''
if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……
'''

num = 2     
if num == 3:            # 判断num的值
    print('boss')        
elif num == 2:
    print('user')
elif num == 1:
    print('worker')
elif num < 0:           # 值小于零时输出
    print('error')
else:
    print('roadman')     # 条件均不成立时输出

num = 9
if num >= 0 and num <= 10:    # 判断值是否在0~10之间
    print('hello')


num = 10
if num < 0 or num > 10:    # 判断值是否在小于0或大于10
    print('hello')
else:
	print('undefine')


num = 8
# 判断值是否在0~5或者10~15之间
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    
    print('hello')
else:
    print('undefine')


var = 100  
if ( var  == 100 ) : print("变量 var 的值为100")
print("Good bye!")


#while语句
'''
while 判断条件：
    执行语句……
'''
count = 0
while (count < 9):
   print('The count is:', count)
   count = count + 1

print("Good bye!")

# continue 和 break 用法

i = 1
while i < 10:   
    i += 1
    if i%2 > 0:     # 非双数时跳过输出
        continue
    print(i)         # 输出双数2、4、6、8、10

i = 1
while 1:            # 循环条件为1必定成立
    print(i)         # 输出1~10
    i += 1
    if i > 10:     # 当i大于10时跳出循环
        break

#死循环
'''
var = 1
while var == 1 :  # 该条件永远为true，循环将无限执行下去
   num = raw_input("Enter a number  :")
   print "You entered: ", num

print "Good bye!"
'''


#while … else 
count = 0
while count < 5:
   print(count, " is  less than 5")
   count = count + 1
else:
   print(count, " is not less than 5")

#简单语句组
flag = 1
while (flag): print('Given flag is really true!');flag=0;
print("Good bye!")

#for语句
'''
for iterating_var in sequence:
   statements(s)
'''
for letter in 'Python':     # 第一个实例
   print('当前字母 :', letter)

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print('当前水果 :', fruit)

print("Good bye!")

#序列索引迭代
fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print('当前水果 :', fruits[index])


#for...else
for num in range(10,20):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print('%d 等于 %d * %d' % (num,i,j))
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print(num, '是一个质数')

#嵌套循环
i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print(i, " 是素数")
   i = i + 1


#break语句
for letter in 'Python':     # First Example
   if letter == 'h':
      break
   print('Current Letter :', letter)
  
var = 10                    # Second Example
while var > 0:              
   print('Current variable value :', var)
   var = var -1
   if var == 5:
      break



#continue语句
for letter in 'Python':     # 第一个实例
   if letter == 'h':
      continue
   print('当前字母 :', letter)

var = 10                    # 第二个实例
while var > 0:              
   var = var -1
   if var == 5:
      continue
   print('当前变量值 :', var)


#pass语句
# 输出 Python 的每个字母
for letter in 'Python':
   if letter == 'h':
      
      pass
      # print('这是 pass 块')
   print('当前字母 :', letter)



#格式字符串
print("My name is %s and weight is %d kg!" % ('Zara', 21))

#时间与日期
import time  # This is required to include time module.

ticks = time.time()
print("Number of ticks since 12:00am, January 1, 1970:", ticks)

localtime = time.localtime(time.time())
print("Local current time :", localtime)

localtime = time.asctime( time.localtime(time.time()) )
print("Local current time :", localtime)

import calendar

cal = calendar.month(2008, 1)
print("Here is the calendar:")
print(cal)



#用Python计算昨天和明天的日期：

import datetime #导入日期时间模块
today = datetime.date.today() #获得今天的日期
print(today) #输出今天日期
#2016-01-25 
yesterday = today - datetime.timedelta(days=1) #用今天日期减掉时间差，参数为1天，获得昨天的日期
print(yesterday)
#2016-01-25 
tomorrow = today + datetime.timedelta(days=1) #用今天日期加上时间差，参数为1天，获得明天的日期
print(tomorrow)
#2016-01-25 
print("昨天:%s， 今天:%s， 明天：%s" % (yesterday, today, tomorrow)) #字符串拼接在一起输出，这3天的日期
#昨天:2016-01-23， 今天:2016-01-24， 明天：2016-01-25

# 日期、字符串互改,  参数默认值
def strf_datetime(time1,form="%Y-%m-%d %H:%M:%S"):
   str=time1.strftime(form)
   return str


def strp_datetime(str,form="%Y-%m-%d %H:%M:%S"):
   time1=datetime.datetime.strptime( str,form )
   return time1

time1=datetime.datetime.now()   
str1=strf_datetime(time1)
str1
time2=strp_datetime(str1)
time2

'''
s_time = "1532573387"

elif re.findall('\d{10,13}',s_time)[0]:
    _t = int(s_time)
    _time = time.localtime(int(_t))
    result_time = time.strftime("%Y-%m-%d %H:%M:%S", _time)

time.strftime("%Y-%m-%d %H:%M:%S"
————————————————
版权声明：本文为CSDN博主「yunlongliang」的原创文章，遵循CC 4.0 BY-SA版权协议，转载请附上原文出处链接及本声明。
原文链接：https://blog.csdn.net/yunlongl/article/details/81225635

'''

#自定义函数
'''
def functionname( parameters ):
   "函数_文档字符串"
   function_suite
   return [expression]		
'''

def printme( str ):
   "打印传入的字符串到标准显示设备上"
   print(str)
   return

#函数调用
printme("我要调用用户自定义函数!");
printme("再次调用同一函数");


# 可写函数说明
def changeme( mylist ):
   "修改传入的列表"
   mylist.append([1,2,3,4]);
   print("函数内取值: ", mylist)
   return
 
# 调用changeme函数
mylist = [10,20,30];
changeme( mylist );
print("函数外取值: ", mylist)


#参数
def printme( str ):
   "打印任何传入的字符串"
   print(str)
   return
 
#调用printme函数
printme()
 
#调用printme函数
printme( str = "My string")


def printinfo( name, age ):
   "打印任何传入的字符串"
   print("Name: ", name)
   print( "Age ", age)
   return
 
#调用printinfo函数
printinfo( age=50, name="miki" );


def printinfo( name, age = 35 ):
   "打印任何传入的字符串"
   print("Name: ", name)
   print("Age ", age)
   return
 
#调用printinfo函数
printinfo( age=50, name="miki" )
printinfo( name="miki" )

#不定长参数
'''
def functionname([formal_args,] *var_args_tuple ):
   "函数_文档字符串"
   function_suite
   return [expression]
'''
def printinfo( arg1, *vartuple ):
   "打印任何传入的参数"
   print("输出: ")
   print(arg1)
   for var in vartuple:
      print(var)
   return
 
# 调用printinfo 函数
printinfo( 10 );
printinfo( 70, 60, 50 );


#匿名函数
'''
lambda [arg1 [,arg2,.....argn]]:expression
'''

sum = lambda arg1, arg2: arg1 + arg2;
# 调用sum函数
print("相加后的值为 : ", sum( 10, 20 ))
print("相加后的值为 : ", sum( 20, 20 ))


#return语句
def sum( arg1, arg2 ):
   # 返回2个参数的和."
   total = arg1 + arg2
   print("函数内 : ", total)
   return total+1;
 
# 调用sum函数
total = sum( 10, 20 );
print("函数外 : ", total) 


#变量的作用范围
total = 0; # 这是一个全局变量
# 可写函数说明
def sum( arg1, arg2 ):
   #返回2个参数的和."
   total = arg1 + arg2; # total在这里是局部变量.
   print("函数内是局部变量 : ", total)
   return total;
 
#调用sum函数
sum( 20, 20 );
print("函数外是全局变量 : ", total)

[i for i in range(5)]

#模块引入
#import module1[, module2[,... moduleN]
#模块名.模块函数

# 导入模块
import support
 
# 现在可以调用模块里包含的函数了
support.print_func("Runoob")

#from modname import name1[, name2[, ... nameN]]
from pandas import DataFrame
from numpy import *



#键盘输入
str = input("Please enter:");
print("你输入的内容是: ", str)


#打开与关闭文件
# 打开一个文件
fo = open("foo.txt", "wb")
print("文件名: ", fo.name)
print("是否已关闭 : ", fo.closed)
print("访问模式 : ", fo.mode)



# 打开一个文件
fo = open("foo.txt", "wb")
print("文件名: ", fo.name)
fo.close()

# 打开一个文件
fo = open("foo.txt", "w")
fo.write("www.runoob.com!\nVery good site!\n")
 
# 关闭打开的文件
fo.close()


# 打开一个文件
fo = open("foo.txt", "r+")
str = fo.read(10);
print("读取的字符串是 : ", str)


# 查找当前位置
position = fo.tell();
print("当前文件位置 : ", position)
 
# 把指针再次重新定位到文件开头
position = fo.seek(0, 0);
str = fo.read(10);
print("重新读取字符串 : ", str)
# 关闭打开的文件
fo.close()



import os
 
# 重命名文件test1.txt到test2.txt。
os.rename( "d:/data/foo.txt", "d:/data/foo2.txt" )


 
# 删除一个已经存在的文件test2.txt
os.remove("d:/data/foo2.txt")



#异常处理
try:
   fh = open("testfile", "w")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print("Error: can\'t find file or read data")
else:
   print("Written content in the file successfully")
   fh.close()


try:
   fh = open("testfile", "r")
   fh.write("This is my test file for exception handling!!")
except IOError:
   print("Error: can\'t find file or read data")
else:
   print("Written content in the file successfully")


try:
   fh = open("testfile", "r")
   fh.write("This is my test file for exception handling!!")
except:
    None
finally:
   print("Error: can\'t find file or read data")


try:
   fh = open("testfile", "w")
   try:
      fh.write("This is my test file for exception handling!!")
   finally:
      print("Going to close the file") 
      fh.close()
except IOError:
   print("Error: can\'t find file or read data")


# def temp_convert(var):
#    try:
#       return int(var)
#    except ValueError as Argument:
#       print( "The argument does not contain numbers\n"+ Argument)

# # Call above function here.
# temp_convert("xyz");


#异常触发
def functionName( level ):
   if level < 1:
      raise "Invalid level!", level
      # The code below to this would not be executed
      # if we raise the exception

try:
   # Business Logic here...
   pass
except "Invalid level!":
   Exception handling here...
else:
   Rest of the code here...

#自定义异常
class Networkerror(RuntimeError):
   def __init__(self, arg):
      self.args = arg

try:
   raise Networkerror("Bad hostname")
except Networkerror as e:
   print(e.args)



def add(a,b):
   a=a+b
   return a
a=4
b=3
c=add(a,b)
print('a=%d,c=%d'%(a,c))
